<template>
	<div class="observer-video">
		<div v-for="stream in remoteStream" id="remoteVideo" :key="stream.id">
			<div class="streamvideo" :id="stream.id + 'div'">
				<video autoplay="autoplay" muted controls class="wh left" :id="stream.id"></video>
				<slot name="checkbox"></slot>
				<slot name="unmuted">
					<img :src="imgSrc" class="muteimg" @click="unmuted(stream.id)" :id="'img' + stream.id" />
				</slot>
				<slot name="stats">
					<div class="stats" v-show="showStats">
						<p>WEBRTC 数据监测</p>
						<ul>
							<li v-if="stream.stats.bytesReceived">
								<span class="des">码率</span>
								<span>{{ stream.stats.bytesReceived }}</span>
							</li>
							<li v-if="stream.stats.rate">
								<span class="des">帧率</span>
								<span>{{ stream.stats.rate }}</span>
							</li>
							<li v-if="stream.stats.packetsRate">
								<span class="des">丢包率</span>
								<span>{{ stream.stats.packetsRate }}</span>
							</li>
							<li v-if="stream.stats.actualWidth && stream.stats.actualHeight">
								<span class="des">分辨率</span>
								<span>{{ stream.stats.actualWidth + 'x' + stream.stats.actualHeight }}</span>
							</li>
							<li v-if="stream.stats.delayMs">
								<span class="des">延时</span>
								<span>{{ stream.stats.delayMs }}</span>
							</li>
							<li v-if="stream.stats.jitterBufferMs">
								<span class="des">抖动</span>
								<span>{{ stream.stats.jitterBufferMs }}</span>
							</li>
						</ul>
					</div>
				</slot>
				<p v-if="stream.agentNo"
					><span>{{ $t('ivcs.agentNum') }}:</span>{{ stream.agentNo }}</p
				>
				<p v-else><span>streamID：</span>{{ stream.id }}</p>
			</div>
		</div>
	</div>
</template>

<script>
import ivcs from '../ivcs-sdk';
const IRtc = ivcs.IRtc;
import { subscriptionGetStats } from '../../static/js/webStatus';
export default {
	name: 'observerVideo',
	props: {
		token: {
			type: String,
			default: ''
		},
		agentNo: {
			type: String,
			default: ''
		},
		streamType: {
			type: String,
			default: ''
		},
		showStats: {
			type: Boolean,
			defualt: () => false
		}
	},
	data() {
		return {
			remoteStream: [],
			imgSrc: require('../../static/images/mute.png'),
			Authorization: null,
			joinSuccess: false,
			subscriptions: new Map(),
			allstats: [],
			intervalfunction: null,
			irtcClient: null,
			webStats: null,
			subIntervalIds: [],
			pubIntervalIds: []
		};
	},
	watch: {
		remoteStream: {
			handler: function(newValue, oldValue) {
				console.log('remoteSteam oldvalue',oldValue);
				this.remoteStream = newValue;
			},
			deep: true
		}
	},

	destroyed() {
		this.leave();
	},
	mounted() {
		let { ConferenceClient } = IRtc.Conference;
		let turnserverUrl = localStorage.getItem('turnserverUrl');
		let turnserverCredential = localStorage.getItem('turnserverCredential');
		let turnserverUsername = localStorage.getItem('turnserverUsername');
		let ccOptions = {
			rtcConfiguration: {
				iceServers: [
					{
						urls: [turnserverUrl],
						credential: turnserverCredential,
						username: turnserverUsername
					}
				]
			}
		};
		this.irtcClient = new ConferenceClient(ccOptions);
		if (this.token) {
			this.join();
		}
	},
	methods: {
		/*取消静音*/
		unmuted(id) {
			var myVid = document.getElementById(id);
			if (myVid.muted) {
				this.imgSrc = require('../../static/images/unmute.png');
				myVid.muted = false;
			} else {
				this.imgSrc = require('../../static/images/mute.png');
				myVid.muted = true;
			}
		},

		/*加入房间*/
		join() {
			var self = this;
			this.irtcClient
				.join(this.token)
				.then(function(resp) {
					console.log('join success', resp);
					self.joinSuccess = true;
					const streams = resp.remoteStreams.filter(stream => {
						if (self.streamType !== '') {
							return stream.source.video == self.streamType;
						} else {
							return stream;
						}
					});
					self.roomremotestream(streams);
					self.addclientEvent(self.irtcClient);
				})
				.catch(function(error) {
					console.log(error);
					self.$Message.error(error);
				});
		},

		/*房间流的处理*/
		roomremotestream(remoteStreams) {
			var self = this;
			remoteStreams.forEach(function(stream, index) {
				console.log(index);
				stream.agentNo = self.agentNo;
				stream.stats = {
					bytesReceived: 0,
					packetsReceived: 0
				};
				console.log(stream);
				// if (stream.origin){
				//   //非mix流
				//   if (stream.settings.video != undefined){
				//     //audio流不显示UI,,video流显示UI
				//     self.remoteStream.push(stream);
				//   }
				//   self.substream(stream);
				// }
				if (stream.settings.video != undefined) {
					//audio流不显示UI,,video流显示UI
					self.remoteStream.push(stream);
				}
				self.substream(stream);
			});
		},

		/*给当前client添加监听事件*/
		addclientEvent(client) {
			let streamaddedListener = eve => {
				let remoteStream = eve.stream;
				console.log('add stream');
				console.log(remoteStream);
				if (remoteStream.origin) {
					if (remoteStream.settings.video != undefined) {
						//audio流不显示UI,,video流显示UI
						this.remoteStream.push(remoteStream);
					}
					this.substream(remoteStream);
				}
			};
			let participantjoinedListener = eve => {
				console.log('new participant joined:', eve);
			};

			let messagereceivedListener = eve => {
				console.log('new message received: ', eve);
			};

			let serverdisconnectedListener = () => {
				console.log('server disconnected');
			};

			client.addEventListener('streamadded', streamaddedListener);
			client.addEventListener('participantjoined', participantjoinedListener);
			client.addEventListener('messagereceived', messagereceivedListener);
			client.addEventListener('serverdisconnected', serverdisconnectedListener);
		},

		/*订阅当前房间里面的流*/
		substream(stream) {
			console.log('开始订阅');
			var self = this;
			//判断流的source
			let audio = true;
			let video = true;
			if (stream.settings.audio == undefined) {
				audio = false;
			}
			if (stream.settings.video == undefined) {
				video = false;
			}
			let options = {
				audio: audio,
				video: video
			};
			console.log(this.irtcClient, options, stream);
			this.irtcClient.subscribe(stream, options).then(
				subscription => {
					console.log('订阅成功');
					console.log(stream.id);
					// 实际丢包数
					let currentSubPacketsReceived = 0;
					// 实际总丢包数
					let currentSubPacketsLost = 0;
					// 当前接收字节数
					let currentSubBytesReceived = 0;
					let sendTime = 3000;
					if (stream.settings.video != undefined) {
						stream.intervalId = subscriptionGetStats(
							subscription,
							sendTime,
							success => {
								stream.stats = success;
								// 实际丢包率计算
								let subPacketsLost = success.packetsLost - currentSubPacketsLost;
								let packetsRate = subPacketsLost / (success.packetsReceived - currentSubPacketsReceived);
								// 实际接收字节数
								let bytesReceived = success.bytesReceived - currentSubBytesReceived;
								currentSubPacketsReceived = success.packetsReceived;
								currentSubBytesReceived = success.bytesReceived;
								stream.stats.packetsRate = (((packetsRate * 100) / sendTime) * 1000).toFixed(2) + '%';
								stream.stats.delayMs = Number((success.delayMs / sendTime) * 1000).toFixed(2) + '%';
								stream.stats.jitterBufferMs ? (stream.stats.jitterBufferMs = Number((success.jitterBufferMs / sendTime) * 1000).toFixed(2)) : '';
								stream.stats.bytesReceived = ((((bytesReceived / 1024) * 8) / sendTime) * 1000).toFixed(2) + 'kb/s';
							},
							err => {
								console.log(err);
								$('#' + stream.id).attr('style', 'display:none;');
								$('#' + stream.id + 'div').attr('style', 'display:none;');
							}
						);
					}
					if (video) {
						self.displayremotestream(stream);
					}
					self.streamEvent(stream); //给流添加监听
					self.subscriptions.set(stream.id, subscription);
					console.log('订阅成功,', self.subscriptions);
					// self.getstatswithStreamId(streamId);//定时获取订阅的流数据
				},
				err => {
					self.$Message.error(err);
					console.log('subscribe failed');
					console.log(`subscribe ${stream.id} failed: ${err}`);
				}
			);
		},

		/*给流添加监听事件*/
		streamEvent(stream) {
			let enedListener = event => {
				console.log(`remote stream ${stream.id} is ended`);
				console.log(event);
				$('#' + stream.id).attr('style', 'display:none;');
				$('#' + stream.id + 'div').attr('style', 'display:none;');
				//this.remoteStream = this.removeArraybyid(this.remoteStream,stream);
			};
			stream.addEventListener('ended', enedListener);
		},

		/*删除数组中某一个id相同的元素*/
		removeArraybyid(_arr, _obj) {
			if (_arr) {
				var length = _arr.length;
				for (var i = 0; i < length; i++) {
					if (_arr[i].id == _obj.id) {
						if (i == 0) {
							_arr.shift(); //删除并返回数组的第一个元素
							return _arr;
						} else if (i == length - 1) {
							_arr.pop(); //删除并返回数组的最后一个元素
							return _arr;
						} else {
							_arr.splice(i, 1); //删除下标为i的元素
							return _arr;
						}
					}
				}
			}
			return _arr;
		},

		/*显示view*/
		displayremotestream(stream) {
			$('#' + stream.id).get(0).srcObject = stream.mediaStream;
		},

		leave() {
			var self = this;
			this.irtcClient.leave().then(
				() => {
					this.irtcClient.clearEventListener('streamadded');
					this.irtcClient.clearEventListener('participantjoined');
					this.irtcClient.clearEventListener('messagereceived');
					this.irtcClient.clearEventListener('serverdisconnected');
					this.irtcClient.clearEventListener('ended');
					// self.$toast('成功离开');
					self.joinSuccess = false;
					self.remoteStream.forEach(item => {
						window.clearInterval(item.intervalId);
					});
					self.remoteStream = []; //删除已经订阅的任何流
					console.log('this.irtcClient leave success');
				},
				err => {
					//self.$toast('离开失败'+err);
					console.log('this.irtcClient leave failed: ', err);
				}
			);
		}
	}
};
</script>

<style scoped>
.observer-video {
	width: 33%;
	display: flex;
	padding: 5px;
	position: relative;
}
.streamvideo {
	margin: 0 5px;
}

.streamvideo {
	position: relative;
}
.streamvideo video {
	width: 100%;
}
.streamvideo img {
	position: absolute;
	bottom: 28%;
	right: 10%;
	width: 10%;
	z-index: 666;
}
.streamvideo p {
	text-align: center;
}
.stats {
	padding: 10px 0;
	width: 180px;
	background-color: #fff;
	border-radius: 5px;
	opacity: 0.8;
	position: absolute;
	z-index: 10;
	top: 8%;
	left: 25%;
}
.stats li {
	width: 90%;
	margin: 0 auto;
	padding: 4px;
	display: flex;
	align-items: center;
	justify-content: space-between;
}
.des {
	font-weight: 700;
}
</style>
